package com.zhou.test.spring.secrity.security.listener;

import com.zhou.common.operator.log.core.constant.OperateActionEnum;
import com.zhou.common.operator.log.core.model.ClientInfo;
import com.zhou.common.operator.log.core.model.OperateLogInfo;
import com.zhou.common.operator.log.core.model.PrincipalInfo;
import com.zhou.common.operator.log.core.resolver.ClientInfoResolver;
import com.zhou.common.operator.log.core.service.OperateLogStorageService;
import com.zhou.test.spring.secrity.model.security.MyUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Date;

/**
 * @author xianfeng
 * @date 2023/5/13 15:30
 */
@Slf4j
@Component
public class MyHttpSessionListener implements HttpSessionListener {

    @Resource
    private ClientInfoResolver clientInfoResolver;

    @Resource
    private OperateLogStorageService logService;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        log.info("sessionCreated={}", se);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        log.info("sessionDestroyed={}", se);
        //todo 记录下线类型，被踢下线的，还是到期后自动下线的
        SecurityContext securityContext = (SecurityContext) se.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        MyUserDetails currentUser = (MyUserDetails) securityContext.getAuthentication().getPrincipal();
        //更新最后一次访问时间
        OperateLogInfo logInfo = new OperateLogInfo();
        logInfo.setClientInfo(new ClientInfo());
        logInfo.setAddTime(new Date());
        PrincipalInfo principalInfo = new PrincipalInfo();
        principalInfo.setUserId(currentUser.getUserId() + "");
        principalInfo.setUserName(currentUser.getUsername());
        principalInfo.setUserPhone(currentUser.getPhone());
        principalInfo.setOrgId(currentUser.getCurrOrgId() + "");
        principalInfo.setOrgName(currentUser.getCurrOrgName() + "");
        logInfo.setPrincipal(principalInfo);
        logInfo.setAction(OperateActionEnum.LOGOUT.getAction());
        logInfo.setOperatingInstruction("登出成功:超时自动登出");
        this.logService.append(logInfo);

    }
}
